package com.polytech.diploma.OracleStatStep;

import java.util.Set;

import org.pentaho.di.core.database.Database;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.row.RowMeta;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStep;
import org.pentaho.di.trans.step.StepDataInterface;
import org.pentaho.di.trans.step.StepInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaInterface;

import com.polytech.diploma.OracleStat.SQLStatData;

public class OracleStatStep extends BaseStep implements StepInterface {

	private OracleStatStepData data = null;
	private OracleStatStepMeta meta = null;
	private Database DBConnection = null;
	
	public OracleStatStep(StepMeta stepMeta, StepDataInterface stepDataInterface,
			int copyNr, TransMeta transMeta, Trans trans) {
		super(stepMeta, stepDataInterface, copyNr, transMeta, trans);
		
        DatabaseMeta dbmeta = transMeta.getDatabase(0);
		DBConnection = new Database(null, dbmeta);
	}
	
	public synchronized boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException
	{
        meta=(OracleStatStepMeta)smi;
        data=(OracleStatStepData)sdi;
        
        if (first) {
            first = false;
            
            data.init(meta, DBConnection);
            
            this.data.outputRowMeta = new RowMeta();
            this.meta.getFields(this.data.outputRowMeta, getStepname(), null, null, this);
        }
        
        Object[] row = getRow(); // get row, blocks when needed!
        
        if (row == null) // no more input to be expected...
        {
        	Set<SQLStatData> statDataRows = data.getStatDataRows();
        	
        	for(SQLStatData statDataRow : statDataRows)
        	{
        		Object[] outputRow = data.writeStatDataRow(statDataRow);
        		putRow(data.outputRowMeta, outputRow);
        	}
        	
            setOutputDone();
            return false;
        }

        data.addStatDataRow(row);
        
        return true;
	}
}
